package com.example.projectdemo.p1;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.example.projectdemo.R;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

/***
 * 动态tab
 * 1.使用LinearLayout时，动画执行完毕，底下会出现白底，布局的原因
 * 2.使用RelativeLayout时，正常
 *
 * 问题一:有个问题是当从位置是3的fragment按返回键回去的时候，fragment0不能保持刚打开的样子
 * 问题二:有个问题是当从位置是3的fragment按返回键回去的时候，topRecyclerView还是fragment3的实例,不是fragment1的(解决)
 */
public class MainActivity extends AppCompatActivity implements BaseFragment.RvScrollListener {

    private TabLayout mTab;
    private ViewPager mViewPager;

    private List<Fragment> mList;
    private List<String> mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        initFragment();
        initView();

        mViewPager.setAdapter(new MyPagerFragmentAdapter(getSupportFragmentManager()));
        //1、将tablayout与viewpager关联起来
        mTab.setupWithViewPager(mViewPager);
        //设置阴影高度
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mTab.setElevation(0);
        }
        //2、移除tablayout的所有tab
        mTab.removeAllTabs();
        //3、重新添加tab
        for (int i = 0; i < mTitle.size(); i++) {
            mTab.addTab(mTab.newTab().setText(mTitle.get(i)));
        }


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                //复位操作

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void initView() {
        mTab = findViewById(R.id.tab);
        mViewPager = findViewById(R.id.tab_item_vp);
    }


    private void initFragment() {
        mList = new ArrayList<>();
        mList.add(new BaseFragment().newInstance("0"));
        mList.add(new BaseFragment().newInstance("1"));
        mList.add(new BaseFragment().newInstance("2"));

        // TODO: 2019/6/1 设置tab的标题是小写，但是运行后的结果显示大写，可以通过修改tablyout的app:tabTextAppearance，改变大小写
        mTitle = new ArrayList<>();
        mTitle.add("a");
        mTitle.add("b");
        mTitle.add("c");
    }

    //上拉状态
    private boolean hasup = true;
    //下滑状态
    private boolean hasdown = true;
    //是否在顶部
    private boolean inTop = true;
    //从fragment传递过来的recycleView
    private RecyclerView topRecyclerView;
    //
    private RecyclerView exitRecyclerView;

    @Override
    public void scrollType(boolean direction) {
        //上拉
        if (direction) {
            hasdown = true;
            //连续上拉，第一次有效
            if (hasup) {
//                ObjectAnimator.ofFloat(mTab, View.TRANSLATION_Y, mTab.getTranslationY(), mTab.getHeight()).setDuration(400).start();
                ObjectAnimator o1 = ObjectAnimator.ofFloat(mTab, View.TRANSLATION_Y, 0, mTab.getHeight());
                ObjectAnimator o2 = ObjectAnimator.ofFloat(mTab, "alpha", 1f, 0f);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.setDuration(400);
                animatorSet.playTogether(o1, o2);
                animatorSet.start();
                hasup = false;
            }
        } else {//下滑
            hasup = true;
            //连续下滑，第一次有效
            if (hasdown) {
//                ObjectAnimator.ofFloat(mTab, View.TRANSLATION_Y, mTab.getTranslationY(), 0).setDuration(400).start();

                ObjectAnimator o1 = ObjectAnimator.ofFloat(mTab, View.TRANSLATION_Y, mTab.getHeight(), 0);
                ObjectAnimator o2 = ObjectAnimator.ofFloat(mTab, "alpha", 0f, 1f);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.setDuration(400);
                animatorSet.playTogether(o1, o2);
                animatorSet.start();
                hasdown = false;
            }
        }
    }

    @Override
    public void inTop(boolean top, RecyclerView recyclerView) {
        Log.e("zxd", "inTop: " + top);
        inTop = top;
        topRecyclerView = recyclerView;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //点击返回键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.i("zxd", "onKeyDown: =============" + mViewPager.getCurrentItem() + inTop);
            //如果当前不是第一个fragmeng则显示第一个
            if (mViewPager.getCurrentItem() != 0) {
                mViewPager.setCurrentItem(0);
                //切换 页面0的rv,否则容易出现问题二
                BaseFragment fragment = (BaseFragment) mList.get(0);
                exitRecyclerView = fragment.getRecyclerView();
                return true;
            }
            //如果当前recycleView没有在顶部则返回顶部
            if (!inTop) {
                if (exitRecyclerView != null && topRecyclerView != exitRecyclerView) {
                    Log.i("zxd", "onKeyDown: topRecyclerView != exitRecyclerView");
                    topRecyclerView = exitRecyclerView;
                }
                LinearLayoutManager layoutManager = (LinearLayoutManager) topRecyclerView.getLayoutManager();
                int firstVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
                Log.i("zxd", "findFirstCompletelyVisibleItemPosition: " + firstVisibleItemPosition);
                if (firstVisibleItemPosition == 0) return super.onKeyDown(keyCode, event);;

                topRecyclerView.smoothScrollToPosition(0);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    private class MyPagerFragmentAdapter extends FragmentPagerAdapter {

        public MyPagerFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return mList.get(i);
        }

        @Override
        public int getCount() {
            return mList.size();
        }
    }
}
